import os
import click
import frappe
from frappe.commands import pass_context
from frappe.commands.site import use
from frappe.installer import _new_site
from frappe.installer import install_app
from .patches import apply_patches

def get_valid_dm_dbname(site_path: str) -> str:
    """生成有效的达梦数据库名称
    达梦数据库的表空间名称不能以下划线开头，
    所以我们在前面加上 'g_' 前缀

    Args:
        site_path: 站点路径

    Returns:
        str: 有效的数据库名称
    """
    import hashlib
    return "g_" + hashlib.sha1(
        os.path.realpath(site_path).encode(),
        usedforsecurity=False
    ).hexdigest()[:16]

@click.command('new-site-dm')
@click.argument('site')
@click.option('--db-host', default=None, help='Database host for DaMeng')
@click.option('--db-port', default=5236, help='Database port for DaMeng')
@click.option('--db-name', default=None, help='Database name for DaMeng')
@click.option('--db-password', default=None, help='Database password for DaMeng')
@click.option('--db-root-username', default='SYSDBA', help='SYSDBA username for DaMeng')
@click.option('--db-root-password', help='SYSDBA password for DaMeng')
@click.option('--admin-password', default=None, help='Administrator password for new site')
@click.option('--verbose', is_flag=True, default=False, help='Verbose output during install')
@click.option('--force', is_flag=True, default=False, help='Force reinstall site')
@click.option('--source_sql', default=None, help='Source SQL file path')
@click.option('--install-app', multiple=True, default=['frappe'], help='Install additional apps')
@click.option('--set-default', is_flag=True, default=False, help='Set the new site as default site')
def new_site_dm(
    site,
    db_root_username=None,
    db_root_password=None,
    admin_password=None,
    verbose=False,
    source_sql=None,
    force=None,
    install_app=None,
    db_name=None,
    db_password=None,
    db_host=None,
    db_port=None,
    set_default=False,
):
    """创建新的达梦数据库站点

    示例:
    \b
    bench new-site-dm mysite.localhost
        --db-host localhost
        --db-port 5236
        --db-password mypassword
    """
    # 先应用达梦数据库补丁
    apply_patches()
    click.echo('Applied DM patches before site creation')

    # 验证补丁是否成功应用
    from frappe.query_builder.utils import db_type_is
    click.echo(f"支持的数据库类型: {[e.value for e in db_type_is]}")
    if hasattr(db_type_is, 'DM'):
        click.echo("达梦数据库补丁应用成功")
    else:
        click.echo("警告: 达梦数据库补丁可能未正确应用")
        return

    # 初始化 frappe
    frappe.init(site=site, new_site=True)

    # 如果没有指定数据库名称，生成一个有效的名称
    if not db_name:
        db_name = get_valid_dm_dbname(frappe.get_site_path())
    # 确保 frappe_dm 在安装列表中
    if 'frappe_dm' not in install_app:
        install_app = list(install_app) + ['frappe_dm']
    
    # 调用原始的 _new_site 命令，但强制使用 dm 类型    
    _new_site(
        db_name,
        site,
        db_root_username=db_root_username,
        db_root_password=db_root_password,
        admin_password=admin_password,
        verbose=verbose,
        install_apps=install_app,
        source_sql=source_sql,
        force=force,
        no_mariadb_socket=False,
        db_password=db_password,
        db_type='dm',  # 强制使用达梦数据库
        db_host=db_host,
        db_port=db_port,
    )
    if set_default:
        use(site)

commands = [
    new_site_dm
] 